package org.edu.modules.growth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.growth.dto.TeacherDTO;
import org.edu.modules.growth.dto.VeJsczExamLogDTO;
import org.edu.modules.growth.entity.VeJsczExam;
import org.edu.modules.growth.entity.VeJsczExamLogLeader;
import org.edu.modules.growth.entity.bo.VeBaseZyzBO;
import org.edu.modules.growth.service.IVeBaseManageService;
import org.edu.modules.growth.service.IVeJsczExamService;
import org.edu.modules.growth.vo.ExamStaticsVo;
import org.edu.modules.growth.vo.VeJsczExamStaticsAllVo;
import org.edu.modules.growth.vo.VeJsczExamStaticsVo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags="教职工评价管理--评教结果管理")
@RestController
@RequestMapping("jsczExam")
@Slf4j
@AllArgsConstructor
public class VeJsczExamController extends BaseController<VeJsczExam, IVeJsczExamService> {

    private IVeJsczExamService mIVeJsczExamService ;

    private IVeBaseManageService mIVeBaseManageService ;

    @ApiOperation(value = "查询领导未评教的教师信息(领导评教页面初始化教师信息)--未实现")
    @GetMapping("/leaderTeacher")
    public Result<?> leaderTeacher( @RequestParam("zyzId")Long zyzId,@RequestParam("stageId")Long stageId)  {
        return Result.OK() ;
    }

    @ApiOperation(value = "提交评教结果(学生)")
    @PostMapping("/submitStudent")
    public Result<?> submitStudent(@RequestBody VeJsczExamLogDTO dto)  {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 查询当前学生对某老师的课程是否已评教
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("stageId",dto.getStageId()) ;
        map.put("teacherUserId",dto.getTeachers().get(0).getTeacherUserId()) ;
        map.put("examUserId",user.getId()) ;
        map.put("kcId",dto.getKcId()) ;
        if( mIVeJsczExamService.isSubmitStudent(map)){
            return Result.error("您已对该教师的课程进行评教！") ;
        }
        // 比较指标数
        if( mIVeJsczExamService.detailNum(dto.getStageId()) == dto.getDetails().size() ){
            mIVeJsczExamService.addExamStudent(dto,user);
            return Result.OK() ;
        }else{
            return Result.error("存在未评审的指标项目！") ;
        }
    }

    @ApiOperation(value = "提交评教结果(老师)")
    @PostMapping("/submitTeacher")
    public Result<?> submitTeacher(@RequestBody VeJsczExamLogDTO dto)  {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if( user.getId().equals(dto.getId().toString())){
            return Result.error("不能对自己进行评教！") ;
        }
        // 查询当前学生对某老师的课程是否已评教
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("stageId",dto.getStageId()) ;
        map.put("teacherUserId",dto.getTeachers().get(0).getTeacherUserId()) ;
        map.put("examUserId",user.getId()) ;
        if( mIVeJsczExamService.isSubmitTeacher(map)){
            return Result.error("您已对该教师的课程进行评教！") ;
        }
        // 比较指标数
        if( mIVeJsczExamService.detailNum(dto.getStageId()) == dto.getDetails().size() ){
            mIVeJsczExamService.addExamTeacher(dto,user);
            return Result.OK() ;
        }else{
            return Result.error("存在未评审的指标项目！") ;
        }
    }

    @ApiOperation(value = "提交评教结果(领导)")
    @PostMapping("/submitLeader")
    public Result<?> submitLeader(@RequestBody VeJsczExamLogDTO dto)  {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 查询当前学生对某老师的课程是否已评教
        QueryWrapper<VeJsczExamLogLeader> wrapper = new QueryWrapper() ;
        wrapper.eq("stageId",dto.getStageId()) ;
        wrapper.in("teacherUserId",dto.getTeachers().stream().
                map(TeacherDTO::getTeacherUserId).collect(Collectors.toList())) ;
        wrapper.eq("examUserId",user.getId()) ;
        if( mIVeJsczExamService.isSubmitLeader(wrapper)){
            return Result.error("您已对该教师的课程进行评教！") ;
        }
        // 比较指标数
        if( mIVeJsczExamService.detailNum(dto.getStageId()) == dto.getDetails().size() ){
            mIVeJsczExamService.addExamLeader(dto,user);
            return Result.OK() ;
        }else{
            return Result.error("存在未评审的指标项目！") ;
        }

    }



    @ApiOperation(value = "评教查询")
    @GetMapping("/select")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "yearCode", value = "年份", dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "zyzId", value = "专业组id", dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "semId", value = "学期Id", dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "type", value = "参评身份 学生、教师、领导（1、2、3）", dataType = "int")
    })
    public Result<VeJsczExamStaticsAllVo> select(@RequestParam("yearCode")Integer yearCode, @RequestParam("semId")Long semId,
                                                 @RequestParam("zyzId")Long zyzId, @RequestParam("type")Integer type ) {
        QueryWrapper<VeJsczExam> wrapper = new QueryWrapper<>() ;
        wrapper.eq("yearCode",yearCode) ;
        wrapper.eq("semId",semId) ;
        wrapper.eq("teacherJyzId",zyzId) ;
        if( type.equals("1")){
            wrapper.gt("studentExamTime",0) ;
        }else if( type.equals("2")){
            wrapper.gt("teacherExamTime",0) ;
        }else{
            wrapper.gt("leaderExamTime",0) ;
        }
        List<VeJsczExam> list = mIVeJsczExamService.list(wrapper) ;
        VeJsczExamStaticsAllVo vo = new VeJsczExamStaticsAllVo() ;
        if( !CollectionUtils.isEmpty(list)){
            List<VeJsczExamStaticsVo> items = Lists.newArrayList() ;
            if( type.equals("1")){
                list.forEach(l->{
                    items.add(new VeJsczExamStaticsVo().setAvg(l.getStudentAvaScore())
                    .setGH(l.getGH()).setXM(l.getXM()).setTeacherUserId(l.getTeacherUserId())) ;
                });
            }else if( type.equals("2")){
                list.forEach(l->{
                    items.add(new VeJsczExamStaticsVo().setAvg(l.getTeacherAvaScore())
                            .setGH(l.getGH()).setXM(l.getXM()).setTeacherUserId(l.getTeacherUserId())) ;
                });
            }else{
                list.forEach(l->{
                    items.add(new VeJsczExamStaticsVo().setAvg(l.getLeaderAvaScore())
                            .setGH(l.getGH()).setXM(l.getXM()).setTeacherUserId(l.getTeacherUserId())) ;
                });
            }
            double d = items.stream().mapToDouble(l->l.getAvg()).average().orElse(0.0) ;
            vo.setAvg(d).setItems(items) ;
        }else{
            vo.setAvg(0.0) ;
        }
        return Result.OK(vo);
    }


    @ApiOperation(value = "评教统计(缺专业组公共接口)")
    @GetMapping("/statics")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "yearCode", value = "年份", dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "semId", value = "学期Id", dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "type", value = "参评身份 学生、教师、领导（1、2、3）", dataType = "int")
    })
    public Result<List<ExamStaticsVo>> statics(@RequestParam("yearCode")Integer yearCode, @RequestParam("semId")Long semId,
                                               @RequestParam("type")Integer type ) {
        List<ExamStaticsVo> staticsList = Lists.newArrayList() ;
        List<VeBaseZyzBO> zyzList = mIVeBaseManageService.zyzAll().getResult() ;
        //获取数据
        QueryWrapper<VeJsczExam> wrapper = new QueryWrapper<>() ;
        wrapper.eq("yearCode",yearCode) ;
        wrapper.eq("semId",semId) ;
        if( type.equals("1")){
            wrapper.gt("studentExamTime",0) ;
        }else if( type.equals("2")){
            wrapper.gt("teacherExamTime",0) ;
        }else{
            wrapper.gt("leaderExamTime",0) ;
        }
        List<VeJsczExam> list = mIVeJsczExamService.list(wrapper) ;
        // 按教研组分组
        Map<Long,List<VeJsczExam>> examMap  ;
        if( !CollectionUtils.isEmpty(list)){
            examMap = list.stream().collect(Collectors.groupingBy(VeJsczExam::getTeacherJyzId)) ;
        }else{
            examMap = Maps.newHashMap() ;
        }
        if( !CollectionUtils.isEmpty(zyzList)){
            zyzList.forEach(l->{
                List<VeJsczExam> arr =examMap.getOrDefault(l.getId(),Lists.newArrayList()) ;
                Long zyzId = l.getId() ;
                String zyzName = l.getYxmc() ;
                Integer addPerson = arr.stream().mapToInt(VeJsczExam::getExamCount).sum() ;
                Integer teacherNum = arr.size() ;
                Double avg;
                if( type.equals("1")){
                    avg = arr.stream().mapToDouble(VeJsczExam::getStudentAvaScore).average().orElse(0.0) ;
                }else if( type.equals("2")){
                    avg = arr.stream().mapToDouble(VeJsczExam::getTeacherAvaScore).average().orElse(0.0) ;
                }else{
                    avg = arr.stream().mapToDouble(VeJsczExam::getLeaderAvaScore).average().orElse(0.0) ;
                }
                staticsList.add(new ExamStaticsVo().setAddPerson(addPerson).setZyzName(zyzName)
                        .setZyzId(zyzId).setAvg(avg).setTeacherNum(teacherNum)) ;
            });
        }
        return Result.OK(staticsList);
    }


}
